// const baseUrl = "http://8.138.113.118:5000"
const baseUrl = 'http://192.168.31.240:7461';

const token = wx.getStorageSync('token') ?? null;

export const request = (url, data, header, customUrl) => {
    wx.showLoading({
        title: '加载中',
        mask: true
    });
    return new Promise((resolve, reject) => {
        wx.request({
            method: 'POST',
            url: customUrl ?? baseUrl + url,
            data: data ?? null,
            header: { Authorization: `${token}` },
            success(res) {
                if (res.statusCode >= 200 && res.statusCode <= 299) {
                    // 从其他接口获取到的响应
                    if (customUrl) {
                        resolve(res.data);
                    }
                    // 从后台请求获取到的响应
                    // res -> {code: number, msg?: string, data: any}
                    if (res.data.code) {
                        resolve(res.data.data);
                    } else {
                        reject(new Error(res.data.msg));
                    }
                } else {
                    reject(new Error(res.data.error));
                }
            },
            fail(err) {
                reject(new Error('网络请求失败'));
            },
            complete() {
                wx.hideLoading();
            }
        });
    });
};

export const uploadRequest = (url, name, data, filePath) => {
    wx.showLoading({
        title: '加载中',
        mask: true
    });
    return new Promise((resolve, reject) => {
        wx.uploadFile({
            filePath: filePath,
            name: name,
            url: baseUrl + url,
            formData: {
                ...data
            },
            header: { Authorization: `${token}` },
            success(res) {
                if (res.statusCode >= 200 && res.statusCode <= 299) {
                    // 从后台请求获取到的响应
                    // res -> {code: number, msg?: string, data: any}
                    const result = JSON.parse(res.data);
                    if (result.code) {
                        resolve(result.data);
                    } else {
                        reject(new Error(result.msg));
                    }
                } else {
                    reject(new Error(res.data.error));
                }
            },
            fail(err) {
                console.log(err);
                reject(new Error('网络请求失败'));
            },
            complete() {
                wx.hideLoading();
            }
        });
    });
};
